import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SingleExpandTreeViewFixed extends Application {
    @Override
    public void start(Stage primaryStage) {
        TreeItem<String> root = new TreeItem<>("根节点");
        root.setExpanded(true);

        for (int i = 1; i <= 5; i++) {
            TreeItem<String> parent = new TreeItem<>("父节点 " + i);
            for (int j = 1; j <= 3; j++) {
                parent.getChildren().add(new TreeItem<>("子节点 " + i + "." + j));
            }
            root.getChildren().add(parent);
        }

        TreeView<String> treeView = new TreeView<>(root);

        treeView.addEventHandler(TreeItem.branchExpandedEvent(), event -> {
            TreeItem<?> expandedItem = event.getTreeItem();

            // 延迟折叠其他节点，避免事件干扰
            Platform.runLater(() -> collapseOthers(root, expandedItem));
        });

        StackPane rootPane = new StackPane(treeView);
        Scene scene = new Scene(rootPane, 400, 300);
        primaryStage.setScene(scene);
        primaryStage.setTitle("每次只展开一个 TreeView 节点");
        primaryStage.show();
    }

    private void collapseOthers(TreeItem<?> current, TreeItem<?> except) {
        if (current == null) return;

        for (TreeItem<?> child : current.getChildren()) {
            if (child != except && !isAncestorOf(child, except)) {
                child.setExpanded(false);
            }
            collapseOthers(child, except);
        }
    }

    private boolean isAncestorOf(TreeItem<?> ancestor, TreeItem<?> node) {
        while (node != null) {
            if (node == ancestor) return true;
            node = node.getParent();
        }
        return false;
    }

    public static void main(String[] args) {
        launch(args);
    }
}